import { writeFile } from 'fs/promises';
import { NextResponse } from 'next/server';
import path from 'path';

export async function POST(request: Request) {
  try {
    const { fileName, base64Data } = await request.json();

    // 移除Base64前缀以获取实际的图片数据
    const base64Image = base64Data.split(';base64,').pop();

    // 确保qrcodes目录存在
    const publicDir = path.join(process.cwd(), 'public');
    const qrcodesDir = path.join(publicDir, 'qrcodes');

    try {
      await writeFile(path.join(qrcodesDir, fileName), base64Image, 'base64');
    } catch (error) {
      console.error('保存二维码失败:', error);
      return NextResponse.json({ error: '保存二维码失败' }, { status: 500 });
    }

    return NextResponse.json({ success: true });
  } catch (error) {
    console.error('处理请求失败:', error);
    return NextResponse.json({ error: '处理请求失败' }, { status: 500 });
  }
}
